/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 ManagedServer.hpp. Created on: 14.09.2009 15:53:35
 */

#ifndef MANAGEDSERVER_HPP_
#define MANAGEDSERVER_HPP_

#include "smartobjects/SmartObjectsDefs.hpp"
#include "INetworkFactory.hpp"
#include "IManagedServer.hpp"
#include "ConnectionHandler.hpp"
#include "ManagedConnection.hpp"
#include "IManagedConnectionFactory.hpp"
#include "IAcceptorListener.hpp"

namespace smartobjects {

class ManagedServer: public IManagedServer, public IManagedConnectionFactory, public IAcceptorListener {
public:
	SO_DLLPRFX ManagedServer(INetworkFactory*);
	SO_DLLPRFX virtual ~ManagedServer();

	SO_DLLPRFX virtual void start();
	SO_DLLPRFX virtual void stop();

	SO_DLLPRFX virtual void setEndpointLocation(IEndpointLocation* poLocation, IEndpointCoordinator* poCoordinator);
	SO_DLLPRFX virtual IEndpointLocation* getEndpointLocation();

	SO_DLLPRFX virtual void addListener(IManagedServerListener*);
	SO_DLLPRFX virtual void delListener(IManagedServerListener*);

	SO_DLLPRFX virtual IManagedConnection* createManagedConnection();
	SO_DLLPRFX virtual void removeManagedConnection(IManagedConnection*);

	SO_DLLPRFX virtual void fireOnConnected(IManagedConnection* poConnection);
	SO_DLLPRFX virtual void fireOnConnected(ConnectionHandler* poHandler);
	SO_DLLPRFX virtual void removeHandler(ConnectionHandler* poHandler);

	SO_DLLPRFX virtual void onAccepted(IConnection*) throw();

protected:
	SO_DLLPRFX void updateAcceptors();
	SO_DLLPRFX void processingPostActionServerListeners();

protected:
	INetworkFactory* m_poNetworkFactory;
	bool m_bStarted;
	boost::recursive_mutex m_mxServer;

	IEndpointLocation* m_poEndpointLocation;
	IEndpointCoordinator* m_poEndpointCoordinator;

	typedef std::list<IManagedServerListener*> ServerListeners;
	ServerListeners m_aServerListeners;
	PostActionListenersContainer<IManagedServerListener> m_oPALServerListeners;
	boost::recursive_mutex m_mxServerListeners;

	typedef boost::unordered_map<std::string, IAcceptor*> AcceptorsMap;
	AcceptorsMap m_mAcceptors;
	typedef std::set<ConnectionHandler*> Handlers;
	Handlers m_aAllHandlers;
	boost::recursive_mutex m_mxAcceptors;

	typedef std::set<IManagedConnection*> ServerConnections;
	ServerConnections m_aConnections;
	boost::recursive_mutex m_mxConnections;
};

}

#endif /* MANAGEDSERVER_HPP_ */
